package com.cxy.common.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

/*********************************************************
 * 文件名称：ConfigUtil.java
 * 系统名称：CXY自定义系统
 * 模块名称：com.cxy.common.config
 * 功能说明：获取自定义配置
 * 开发人员 @author：caoxy31978
 * 开发时间 @date：2023/7/4 11:04
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
@Order(101)
@Slf4j
public class ConfigUtils implements EnvironmentPostProcessor {
    private static Environment ENVIRONMENT;
    private final Log deferredLog;

    public ConfigUtils(DeferredLogFactory logFactory) {
        this.deferredLog = logFactory.getLog(ConfigUtils.class);
    }
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        ENVIRONMENT = environment;
    }
    public static String get(String key) {
        return get(key,String.class,null);
    }

    public static String get(String key, String defaultValue) {
        return get(key,String.class,defaultValue);
    }

    public static <T> T get(String key, Class<T> targetType) {
        return get(key,targetType,null);
    }

    public static <T> T get(String key, Class<T> targetType, T defaultValue) {
        if (null == ENVIRONMENT) {
            log.warn("The application environment is Null, please check.");
            return defaultValue;
        } else {
            try {
                return ENVIRONMENT.getProperty(key, targetType, defaultValue);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    }

    public static String getAppHost() {
        return get("app.host");
    }
}
